﻿using Client.Interfaces;
using System.IO;
using System.Reflection;
using System;

namespace Client.Controllers
{
    internal class LoginController : ILoginController
    {
        private IMainController _mainController;
        private ILoginView _view;

        public LoginController(IMainController controller, ILoginView view)
        {
            _mainController = controller;
            _view = view;
        }

        #region ILoginC Members

        public bool LoginUser(string username, string password)
        {
            // test for username and password
            secureMessengerServer.IsMessengerServerClient server = new Client.secureMessengerServer.IsMessengerServerClient("secureMessengerServerEndpoint");
            try
            {
                server.ClientCredentials.ClientCertificate.Certificate = Certificate.CertificateLoader.GetClientCertificate(password);
            }
            catch (FileNotFoundException)
            {
                _view.Message = "Could not open client certificate";
                return false;
            }
            catch (Exception)
            {
                _view.Message = "Password wrong for certificate";
                return false;
            }

            try
            {
                string port = System.Configuration.ConfigurationSettings.AppSettings["port"];
                if (server.Login(username, password, port))
                {
                    _mainController.LoginSucces(username, password);
                    return true;
                }
                _view.Message = "Wrong username or password";
            }
            catch (Exception)
            {
                _view.Message = "Could not connect";
            }
            return false;
        }

        #endregion
    }
}
